package com.writing.controller;

import com.writing.annotation.RequireAdmin;
import com.writing.common.Result;
import com.writing.entity.ApiConfig;
import com.writing.service.ApiConfigService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * API配置控制器
 */
@RestController
@RequestMapping("/api-configs")
@RequiredArgsConstructor
public class ApiConfigController {

    private final ApiConfigService apiConfigService;

    /**
     * 获取用户的所有API配置（管理员使用）
     */
    @GetMapping
    public Result<List<ApiConfig>> getApiConfigs(HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        try {
            // 管理员可以获取所有配置
            String role = (String) request.getAttribute("role");
            if ("ADMIN".equals(role)) {
                List<ApiConfig> configs = apiConfigService.getAllConfigs();
                return Result.success(configs);
            } else {
                // 普通用户只能看到自己创建的配置
                List<ApiConfig> configs = apiConfigService.getConfigsByUserId(userId);
                return Result.success(configs);
            }
        } catch (Exception e) {
            return Result.error("获取API配置列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取所有启用的公共API配置（所有用户都可以使用）
     */
    @GetMapping("/public")
    public Result<List<ApiConfig>> getPublicApiConfigs() {
        try {
            List<ApiConfig> configs = apiConfigService.getEnabledConfigs();
            return Result.success(configs);
        } catch (Exception e) {
            return Result.error("获取公共API配置列表失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID获取API配置详情
     */
    @GetMapping("/{id}")
    public Result<ApiConfig> getApiConfig(@PathVariable Long id, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        try {
            ApiConfig config = apiConfigService.getConfigById(id);
//            if (config == null || !config.getUserId().equals(userId)) {
//                return Result.error("配置不存在或无权限访问");
//            }
            return Result.success(config);
        } catch (Exception e) {
            return Result.error("获取API配置详情失败: " + e.getMessage());
        }
    }

    /**
     * 创建API配置（仅管理员）
     */
    @RequireAdmin(message = "需要管理员权限才能创建API配置")
    @PostMapping
    public Result<ApiConfig> createApiConfig(@RequestBody @Valid ApiConfig apiConfig,
                                           HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        try {
            apiConfig.setUserId(userId);
            ApiConfig createdConfig = apiConfigService.createConfig(apiConfig);
            return Result.success("创建成功", createdConfig);
        } catch (Exception e) {
            return Result.error("创建API配置失败: " + e.getMessage());
        }
    }

    /**
     * 更新API配置（仅管理员）
     */
    @RequireAdmin(message = "需要管理员权限才能更新API配置")
    @PutMapping("/{id}")
    public Result<ApiConfig> updateApiConfig(@PathVariable Long id,
                                           @RequestBody @Valid ApiConfig apiConfig,
                                           HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        try {
            ApiConfig existingConfig = apiConfigService.getConfigById(id);
            if (existingConfig == null) {
                return Result.error("配置不存在");
            }

            apiConfig.setId(id);
            apiConfig.setUserId(existingConfig.getUserId()); // 保持原用户的关联
            ApiConfig updatedConfig = apiConfigService.updateConfig(apiConfig);
            return Result.success("更新成功", updatedConfig);
        } catch (Exception e) {
            return Result.error("更新API配置失败: " + e.getMessage());
        }
    }

    /**
     * 删除API配置（仅管理员）
     */
    @RequireAdmin(message = "需要管理员权限才能删除API配置")
    @DeleteMapping("/{id}")
    public Result<Void> deleteApiConfig(@PathVariable Long id, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        try {
            ApiConfig config = apiConfigService.getConfigById(id);
            if (config == null) {
                return Result.error("配置不存在");
            }

            apiConfigService.deleteConfig(id);
            return Result.success();
        } catch (Exception e) {
            return Result.error("删除API配置失败: " + e.getMessage());
        }
    }

    /**
     * 复制API配置（仅管理员）
     */
    @RequireAdmin(message = "需要管理员权限才能复制API配置")
    @PostMapping("/{id}/duplicate")
    public Result<ApiConfig> duplicateApiConfig(@PathVariable Long id, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        try {
            ApiConfig config = apiConfigService.getConfigById(id);
            if (config == null) {
                return Result.error("配置不存在");
            }

            ApiConfig duplicatedConfig = apiConfigService.duplicateConfig(id);
            return Result.success("复制配置成功", duplicatedConfig);
        } catch (Exception e) {
            return Result.error("复制配置失败: " + e.getMessage());
        }
    }

    /**
     * 测试API配置连接
     */
    @PostMapping("/{id}/test")
    public Result<String> testApiConfig(@PathVariable Long id, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        try {
            ApiConfig config = apiConfigService.getConfigById(id);
            if (config == null) {
                return Result.error("配置不存在");
            }
            
            // 只有管理员或配置所有者可以测试
            String role = (String) request.getAttribute("role");
            boolean isAdmin = "ADMIN".equals(role);
            if (!isAdmin && !config.getUserId().equals(userId)) {
                return Result.error("配置不存在或无权限访问");
            }

            boolean isValid = apiConfigService.testConnection(config);
            if (isValid) {
                return Result.success("连接测试成功", "API配置连接正常");
            } else {
                return Result.error("连接测试失败");
            }
        } catch (Exception e) {
            return Result.error("连接测试失败: " + e.getMessage());
        }
    }
}
